<template>
  <view class="purchase-order-list">
    <!-- 搜索过滤区域 -->
    <view class="filter-container">
      <view class="filter-section">
        <view class="filter-group">
          <view class="filter-label">订单日期</view>
          <view class="filter-input">
            <uni-datetime-picker
                type="date"
                v-model="searchDate"
                :default-date="currentDate"
                @change="onDateChange"
                placeholder="选择日期"
                class="date-picker"
            ></uni-datetime-picker>
          </view>
        </view>

        <view class="filter-group">
          <view class="filter-label">订单状态</view>
          <view class="filter-input">
            <uni-data-select
                v-model="selectedStatus"
                :localdata="statusOptions"
                @change="onStatusChange"
                placeholder="全部状态"
                class="status-picker"
            ></uni-data-select>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view class="empty-tip" v-if="orders.length === 0">
        <text>暂无符合条件的订单</text>
      </view>

      <view
          class="order-item"
          v-for="order in orders"
          :key="order.orderId"
          @click="viewOrderDetail(order.orderId)"
      >
        <view class="order-header">
          <text class="order-number">订单号: {{ order.orderSerialNumber }}</text>
          <text class="order-type" :class="getOrderTypeClass(order.orderType)">{{
              getOrderTypeText(order.orderType)
            }}
          </text>
        </view>

        <view class="order-meta">
          <view class="meta-item">
            <text class="meta-label">订单日期</text>
            <text class="meta-value">{{ order.orderDate }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">总采购金额</text>
            <text class="meta-value price">{{ order.totalPurchasePrice }}</text>
          </view>
        </view>

        <view class="order-status">
          <text class="status-label">订单状态</text>
          <text class="status-value" :class="getStatusClass(order.status)">{{ getStatusText(order.status) }}</text>
        </view>
      </view>
    </view>

    <!-- 分页控件 -->
    <view class="pagination" v-if="orders.length > 0">
      <uni-load-more
          :content-text="loadMoreText"
          :status="loadStatus"
          @clickloadmore="loadMore"
      ></uni-load-more>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchData: {},
      searchDate: '',
      currentDate: '',
      selectedStatus: 'all',
      statusOptions: [
        {text: '全部', value: 'all'},
        {text: '待处理', value: 'PENDING'},
        {text: '已完成', value: 'COMPLETED'},
        {text: '已取消', value: 'CANCELLED'}
      ],
      orders: [],
      page: 1,
      pageSize: 10,
      total: 0,
      loadStatus: 'more',
      loadMoreText: {
        contentdown: '上拉加载更多',
        contentrefresh: '加载中...',
        contentnomore: '没有更多数据'
      }
    }
  },
  onLoad() {
    this.currentDate = this.getTodayDate();
    this.searchDate = this.currentDate;
    this.loadOrders();
  },
  methods: {
    // 获取当天日期
    getTodayDate() {
      const date = new Date();
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 日期选择变化时直接加载数据
    onDateChange(e) {
      this.searchDate = e.mp.detail.value;
      this.loadOrders();
    },

    // 状态选择变化时直接加载数据
    onStatusChange(e) {
      this.selectedStatus = e.mp.detail.value;
      this.loadOrders();
    },

    // 加载订单数据
    loadOrders() {
      this.page = 1; // 重置页码
      this.loadStatus = 'loading';
      this.req({
        url: '/purchase/list',
        method: 'POST',
        data: this.searchData
      }).then(res => {
        this.orders  = res.rows
        this.total = res.total;
        this.loading = false;
        this.loadStatus = this.page * this.pageSize >= this.total ? 'nomore' : 'more';
      })
    },

    // 加载更多
    loadMore() {
      if (this.loadStatus !== 'more') return;
      this.page++;
      this.loadStatus = 'loading';

      setTimeout(() => {
        const newOrders = this.getMockOrders(
            this.searchDate,
            this.page,
            this.selectedStatus
        );

        this.orders = [...this.orders, ...newOrders];
        this.loadStatus = this.page * this.pageSize >= this.total ? 'nomore' : 'more';
      }, 500);
    },

    // 获取订单类型样式
    getOrderTypeClass(type) {
      const classes = {
        'PURCHASE': 'type-purchase',
        'RETURN': 'type-return',
        'DAMAGE': 'type-damage',
        'LOSS': 'type-loss'
      };
      return classes[type] || 'type-default';
    },

    // 获取订单状态样式
    getStatusClass(status) {
      const classes = {
        'PENDING': 'status-pending',
        'COMPLETED': 'status-completed',
        'CANCELLED': 'status-cancelled'
      };
      return classes[status] || 'status-default';
    },

    // 获取订单类型中文文本
    getOrderTypeText(type) {
      const texts = {
        'PURCHASE': '采购',
        'RETURN': '退货',
        'DAMAGE': '损坏',
        'LOSS': '损耗'
      };
      return texts[type] || type;
    },

    // 获取订单状态中文文本
    getStatusText(status) {
      const texts = {
        'PENDING': '待处理',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      };
      return texts[status] || status;
    },

    // 查看订单详情
    viewOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/purchase/order-detail?id=${orderId}`
      });
    },

    // 获取模拟订单数据
    getMockOrders(date, page, statusFilter) {
      const isToday = date === this.currentDate;
      const baseOrders = [
        {
          orderId: 1,
          orderSerialNumber: 'PO20230522001',
          orderType: 'PURCHASE',
          orderDate: isToday ? this.currentDate : '2023-05-21',
          totalPurchasePrice: 258.50,
          status: 'COMPLETED'
        },
        {
          orderId: 2,
          orderSerialNumber: 'PO20230522002',
          orderType: 'PURCHASE',
          orderDate: isToday ? this.currentDate : '2023-05-21',
          totalPurchasePrice: 136.80,
          status: 'PENDING'
        },
        {
          orderId: 3,
          orderSerialNumber: 'PO20230522003',
          orderType: 'RETURN',
          orderDate: isToday ? this.currentDate : '2023-05-21',
          totalPurchasePrice: 89.20,
          status: 'CANCELLED'
        },
        {
          orderId: 4,
          orderSerialNumber: 'PO20230522004',
          orderType: 'PURCHASE',
          orderDate: isToday ? this.currentDate : '2023-05-21',
          totalPurchasePrice: 450.30,
          status: 'PENDING'
        },
        {
          orderId: 5,
          orderSerialNumber: 'PO20230522005',
          orderType: 'PURCHASE',
          orderDate: isToday ? this.currentDate : '2023-05-21',
          totalPurchasePrice: 189.70,
          status: 'COMPLETED'
        }
      ];

      const filteredOrders = statusFilter === 'all'
          ? baseOrders
          : baseOrders.filter(order => order.status === statusFilter);

      const start = (page - 1) * this.pageSize;
      return filteredOrders.slice(start, start + this.pageSize);
    }
  }
}
</script>

<style>
.purchase-order-list {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.filter-container {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.filter-section {
  padding: 20rpx;
}

.filter-group {
  display: flex;
  margin-bottom: 15rpx;
}

.filter-group:last-child {
  margin-bottom: 0;
}

.filter-label {
  font-size: 28rpx;
  color: #666;
  width: 120rpx;
  line-height: 70rpx;
  text-align: right;
  margin-right: 15rpx;
}

.filter-input {
  flex: 1;
}

.date-picker, .status-picker {
  width: 100%;
  height: 70rpx;
  line-height: 70rpx;
  //border: 1rpx solid #e8e8e8;
  border-radius: 35rpx;
  padding: 0 25rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #f9f9f9;
  box-sizing: border-box;
  display: block;
}

.status-picker {
  background-image: url('data:image/svg+xml;charset=utf-8,<svg viewBox="0 0 1024 1024" width="24" height="24" fill="#666"><path d="M512 768l448-448-64-64L512 640l-384-384-64 64z"/></svg>');
  background-repeat: no-repeat;
  background-position: right 25rpx center;
  background-size: 24rpx;
}

.order-list {
  margin-bottom: 20rpx;
}

.empty-tip {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 25rpx 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
}

.order-item:active {
  transform: scale(0.99);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.order-number {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.order-type {
  font-size: 24rpx;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-weight: 500;
}

.type-purchase {
  background-color: #e6f7ff;
  color: #007aff;
}

.type-return {
  background-color: #fff3f3;
  color: #e54d42;
}

.type-damage, .type-loss {
  background-color: #f8f3e6;
  color: #d8b585;
}

.type-default {
  background-color: #f0f0f0;
  color: #666;
}

.order-meta {
  display: flex;
  margin-bottom: 20rpx;
}

.meta-item {
  flex: 1;
}

.meta-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 5rpx;
}

.meta-value {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.price {
  color: #e54d42;
}

.order-status {
  display: flex;
  align-items: center;
}

.status-label {
  font-size: 26rpx;
  color: #666;
  margin-right: 10rpx;
}

.status-value {
  font-size: 30rpx;
  font-weight: 500;
}

.status-pending {
  color: #ff9500;
}

.status-completed {
  color: #00b42a;
}

.status-cancelled {
  color: #999;
}

.status-default {
  color: #666;
}

.pagination {
  padding: 20rpx 0;
  text-align: center;
}

/* 加载状态动画 */
.loading-placeholder {
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}
</style>